{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Annotate Comics/Manga\n",
    "Download comictextdetector.pt and put it into data directory.\n",
    "Run next block to generate following annotations for data\\examples\\AisazuNihaIrarenai-003.jpg:\n",
    "- AisazuNihaIrarenai-003.txt: yolo format bounding boxes of english&japanese text block bounding boxes. 0 is eng.\n",
    "- mask-AisazuNihaIrarenai-003.png\n",
    "- line-AisazuNihaIrarenai-003.txt: icdar format bboxes of text lines."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 1/1 [00:04<00:00,  4.78s/it]\n"
     ]
    }
   ],
   "source": [
    "from inference import model2annotations\n",
    "\n",
    "img_dir = r'data/examples'\n",
    "model_path = r'data/comictextdetector.pt'\n",
    "img_dir = r'data/examples'                              # can be dir list\n",
    "save_dir = r'data/examples/annotations'\n",
    "model2annotations(model_path, img_dir, save_dir, save_json=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate synthetic data\n",
    "- current rendering script won't handle characters missing from fonts.\n",
    "- Please use no-text images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 10/10 [00:12<00:00,  1.23s/it]\n"
     ]
    }
   ],
   "source": [
    "from text_rendering import ComicTextSampler, render_comictext, ALIGN_LEFT, ALIGN_CENTER\n",
    "import copy\n",
    "\n",
    "ja_sampler_dict = {\n",
    "                'num_txtblk': 20,\n",
    "                'font': {\n",
    "                        'font_dir': 'data/examples/fonts',   # font file directory\n",
    "                        'font_statics': 'data/font_statics_en.csv',     # Just a font list file, please create your own list and ignore the last two cols.\n",
    "                        'num': 1200,     # first 500 of the fontlist will be used \n",
    "\n",
    "                        # params to mimic comic/manga text style\n",
    "                        'size': {'value': [0.02, 0.03, 0.15],\n",
    "                                'prob': [1, 0.4, 0.15]},\n",
    "                        'stroke_width': {'value': [0, 0.1, 0.15],\n",
    "                                        'prob': [1, 0.5, 0.2]},\n",
    "                        'color': {'value': ['black', 'white', 'random'],\n",
    "                                'prob': [1, 1, 0.4]},\n",
    "                },\n",
    "                'text': {\n",
    "                        'lang': 'ja',   # render japanese, 'en' for english\n",
    "                        'orientation': {'value': [1, 0],    # 1 is vertical text.\n",
    "                                                'prob': [1, 0.3]},\n",
    "                        'rotation': {'value': [0, 30, 60],\n",
    "                                                'prob': [1, 0.3, 0.1]},\n",
    "                        'num_lines': {'value': [0.15],\n",
    "                                'prob': [1]}, \n",
    "                        'length': {'value': [0.3],\n",
    "                                'prob': [1]},\n",
    "                        'min_num_lines': 1,\n",
    "                        'min_length': 3,\n",
    "                        'alignment': {'value': [ALIGN_LEFT, ALIGN_CENTER],\n",
    "                                'prob': [0.3, 1]}\n",
    "                }\n",
    "        }\n",
    "\n",
    "jp_cts = ComicTextSampler((845, 1280), ja_sampler_dict, seed=0)\n",
    "eng_dict = copy.deepcopy(ja_sampler_dict)\n",
    "eng_dict['text']['lang'] = 'en'\n",
    "eng_dict['text']['orientation'] = {'value': [1, 0],\n",
    "                                'prob': [0, 1]}\n",
    "eng_cts = ComicTextSampler((845, 1280), eng_dict, seed=0)\n",
    "\n",
    "img_dir = r'data/examples'\n",
    "save_dir = r'data/examples/annotations'\n",
    " \n",
    "render_comictext([eng_cts, jp_cts], img_dir, save_dir=save_dir, save_prefix=None, render_num=10, label_dir=None, show=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training\n",
    "### Train Text Block Detector\n",
    "Train yolov5s using official repo of yolov5, assume the trained model is 'yolov5sblk.pt', go to the root directory of yolov5 and run following code.\n",
    "\n",
    "``` python\n",
    "import torch\n",
    "m = torch.load('yolov5sblk.pt')['model']\n",
    "save_dict = {\n",
    "    'cfg': m.yaml,\n",
    "    'weights': m.state_dict()\n",
    "}\n",
    "torch.save(save_dict, 'yolov5sblk.ckpt')\n",
    "```\n",
    "### Train Text Segmentation Head\n",
    "1. Put yolov5sblk.ckpt into data.   \n",
    "2. Refer to train_seg.py for further details.  \n",
    "\n",
    "### Train DBHead\n",
    "Please refer to train_db.py.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Concat weights & export as onnx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from utils.export import *\n",
    "concate_models('data/yolov5sblk.ckpt', 'data/unet_best.ckpt', 'data/db_best.ckpt', 'data/textdetector.pt')\n",
    "\n",
    "batch_size, imgsz = 1, 1024\n",
    "cuda = torch.cuda.is_available()\n",
    "device = 'cpu'\n",
    "im = torch.zeros(batch_size, 3, imgsz, imgsz).to(device)\n",
    "model_path = r'data/textdetector.pt'\n",
    "model = TextDetBase(model_path, device=device).to(device)\n",
    "export_onnx(model, im, model_path, 11)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "545b34d9a5e72e2b90b819a16ec22002dd3dc9d66aaf1029c3177c6408a5603b"
  },
  "kernelspec": {
   "display_name": "Python 3.9.7 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
